package org.mineground.commands.player;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.mineground.Main;
import org.mineground.Utilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LastSeen implements CommandExecutor {
    private static final Logger ExceptionLogger = LoggerFactory.getLogger(LastSeen.class);
    
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) throws CommandException {
	Player player = (Player) sender;

	if (args.length == 0) {
	    player.sendMessage(ChatColor.RED + "* Usage: '/lastseen <Player>'");
	    return true;
	}

	try {
	    PreparedStatement statement = Main.getInstance().getDatabaseHandler().getConnection().prepareStatement("SELECT last_online FROM lvm_players WHERE login_name = ?");
	    statement.setString(1, args[0]);
	    statement.execute();

	    ResultSet result = statement.getResultSet();

	    if (!result.next()) {
		player.sendMessage(ChatColor.RED + "* Error: No result.");
		return true;
	    }

	    Date date = result.getDate(1);

	    java.util.Date now = new java.util.Date();
	    java.util.Date dif = new java.util.Date(date.getTime());

	    StringBuilder out = new StringBuilder();
	    out.append(ChatColor.DARK_PURPLE);
	    out.append(args[0]);
	    out.append(" was last online at ");
	    out.append(date.toString());
	    out.append(" (");
	    out.append(Utilities.daysBetween(dif, now));
	    out.append(" days ago).");

	    player.sendMessage(out.toString());
	}

	catch (Exception exception) {
	    ExceptionLogger.error("Exception caught", exception);
	}

	return true;
    }
}